import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import localCache from '@/utils/cache'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/home',
    meta: {
      isPermission: true,
    },
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/home/home.vue'),
    meta: {
      isPermission: true,
    },
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('@/views/about/about.vue'),
    meta: {
      isPermission: true,
    },
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue'),
    meta: {
      isPermission: true,
    },
  },
  {
    path: '/protfolio',
    name: 'protfolio',
    component: () => import('@/views/protfolio/protfolio.vue'),
    meta: {
      isPermission: false,
    },
  },
  {
    path: '/project-detail/:id',
    name: 'details',
    component: () => import('@/views/protfolio/details/project-detail.vue'),
    props: true,
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('@/views/not-found/not-found.vue'),
  },
  {
    path: '/user',
    name: 'user',
    redirect: '/user/project-management',
    component: () => import('@/views/user/user.vue'),
    children: [
      {
        path: 'project-management',
        name: 'management',
        component: () =>
          import('@/views/user/project-management/project-management.vue'),
      },
      {
        path: 'project-edit/:data?',
        name: 'edit',
        component: () => import('@/views/user/project-edit/project-edit.vue'),
        props: true,
      },
    ],
  },
]

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
})
router.beforeEach((to) => {
  // 获取当前路由path（不带/的）
  const currentRouter = to.path.split('/')[1]
  if (router.hasRoute(currentRouter)) {
    if (to.path !== '/login') {
      const token = localCache.getCache('token')
      // if (!token) {
      if (!token) {
        // 没有登录
        if (!to.meta.isPermission) {
          // 登录才可以访问的页面
          return '/login'
        }
        // 没有登录才可以访问的页面
      }
    }

    // if (!to.meta.isPermission) return '/login'
  }
})

export default router
